package cn.tedu.blog.server.config;

import cn.tedu.blog.server.filter.JwtAuthorizationFilter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;


/**
 * @Author: 雷茂林
 * @Date:2022/7/15 21:59
 * @Description:
 */
@Slf4j
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)//下方注解表示以开启全局的授权访问检查，此配置为一次性配置
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    JwtAuthorizationFilter jwtAuthorizationFilter;

    @Bean
    public PasswordEncoder passwordEncoder() {
        log.debug("创建密码编码器组件：BCryptPasswordEncoder");
        return new BCryptPasswordEncoder();
    }


    @Bean
    @Override
    protected AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 在配置路径时可以使用星号作为通配符
        // 使用 /* 只能匹配层级路径，例如/user或/brand，不可以匹配多层级
        // 使用 /** 可以匹配若干层级路径

        // 白名单，不需要登录就可以访问
        String[] urls = {
                "/api/articles/list/*",
                "/system/users/login",
                "/doc.html",
                "/**/*.css",
                "/captcha",
                "/**/*.js",
                "/favicon.ico",
                "/upload",
                "/v2/api-docs",
                "/swagger-resources"
        };

        http.cors();
        http.csrf().disable(); // 禁用防止跨域访问，如果无此配置，白名单路径的异步访问也会出现403

        http.authorizeRequests()    //请求需要被授权才可以访问
                .antMatchers(HttpMethod.OPTIONS,"/**")
                .permitAll()
                .antMatchers(urls) //匹配某些路径，白名单
                .permitAll()    //直接允许访问（不需要经过认证和授权）
                .anyRequest()
                .authenticated();

        //添加处理JWT的过滤器，必须执行在处理用户名、密码的过滤器之前
        http.addFilterBefore(jwtAuthorizationFilter, UsernamePasswordAuthenticationFilter.class);
    }
}
